package com.mengniu.commerce.collect.controller;

import com.mengniu.commerce.collect.service.IPushStrategy;
import com.mengniu.commerce.collect.util.RestTemplateUtil;
import com.mengniu.commerce.common.core.domain.R;
import com.mengniu.commerce.idempotent.annotation.RepeatSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * @Description: 有赞获取授权店铺Code
 * @Param:
 * @return:
 * @Author: zfw
 * @Date: 2023/11/23
 * @Date: 19:23
 */
@RestController
@RequestMapping("/getCode")
@Slf4j
public class GetAuthorizationCodeController {

    @Resource
    RestTemplateUtil restTemplateUtil;


    /**
     * 获取有赞授权码
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/getAuthCode")
    public String getAuthCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("GBK");
        response.setCharacterEncoding("GBK");
        String code = request.getParameter("code");
        //获取有赞token落库
        restTemplateUtil.getTokenByCode(code);
        return code;
    }

    /**
     * 获取有赞Token
     *
     * @return
     */
    @GetMapping("/getToken")
    public String getToken() {
        String token = restTemplateUtil.getToken();
        return token;
    }

    /***
     * @Description: 分发有赞推送的消息 todo
     * @Param: [entity, eventSign, eventType, clientId]
     * @return: java.lang.Object
     * @Author: zfw
     * @Date: 2023/11/28
     * @Date: 10:56
     */
    @RequestMapping("/push")
    @RepeatSubmit(interval = 1000, message = "分发有赞推送的消息禁止重复", timeUnit = TimeUnit.MILLISECONDS)
    public R<Object> receiveMessages(@RequestBody String entity,
                                     @RequestHeader("Event-Sign") String eventSign,
                                     @RequestHeader("Event-Type") String eventType,
                                     @RequestHeader("Client-Id") String clientId) throws IOException {

        log.info("接收消息推送的消息为entity:{},eventSign:{},eventType:{},clientId:{}", entity, eventSign, eventType, clientId);
        return R.ok(IPushStrategy.push(entity, eventType, eventSign));
    }


    @GetMapping("/getToken1")
    public String getToken(String code){
      return restTemplateUtil.getTokenByCode(code);
    }
}


